<?php

namespace App\Listeners;

use App\Constant\JpushCode;
use App\Constant\QueueKey;
use App\Events\JpushNoticeEvent;
use App\Facades\Jpush;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class JpushNoticeListener implements ShouldQueue
{
    //需要手动访问监听器下面队列任务的 delete 和 release 方法
    use InteractsWithQueue;

    public $queue = QueueKey::QUEUE_JPUSH_NOTICE;

    /**
     * 任务最大尝试次数。
     *
     * @var int
     */
    public $tries = 5;

    /**
     * 任务运行的超时时间。
     *
     * @var int
     */
    public $timeout = 300; //秒数

    /**
     * Handle the event.
     *
     * @param  JpushNoticeEvent  $event
     * @return void
     */
    public function handle(JpushNoticeEvent $event)
    {
        $notification = $event->notification;
        $push = Jpush::push();
        switch ($notification['audience']) {
            case JpushCode::AUDIENCE_TYPE_ONE: //所有用户
                $push->addAllAudience();
                break;
            case JpushCode::AUDIENCE_TYPE_TWO: //目标用户
            case JpushCode::AUDIENCE_TYPE_THREE: //标签用户
                $push->addRegistrationId($notification['to']);
                break;
        }

        $push->setPlatform('all')
            ->AndroidNotification($notification['body'], [
                'title' => $notification['title'],
                'extras' =>$notification['extras'],
            ])
            ->iosNotification([
                'title' => $notification['title'],
                'body' => $notification['body'],
            ],[
                'extras' =>$notification['extras'],
            ])
            ->send();
        Log::debug('jpush_send_log', ['notification' => $event->notification]);
    }
}